import { defineStore } from 'pinia'
import { getResumeModelList, addResume, addResumeModel, detResumeModel } from '@/api/module.js'

export const useResumeStore = defineStore('resume', {
  state: () => ({
    // 简历模板信息
    template: {
      id: '', // 模板ID
      modelName: '', // 模板名称
      type: 'default', // 模板类型：default-通用，it-IT互联网，finance-金融，education-教育等
    },
	// 简历id
	resumeId:'',
    // 个人信息
    personalInfo: {
      avatar: '', // 头像
      name: '', // 姓名
      gender: 'male', // 性别：male-男，female-女
      maritalStatus: 'isMarital', // 性别：male-男，female-女
      birthday: '', // 出生日期
      location: '', // 现住城市
      phone: '', // 手机号码
      email: '', // 邮箱
      ethnicGroup: '', // 民族
      politicalStatus: '', // 政治面貌
    },
    // 工作经历
    workExperiences: [],
    // 教育经历
    educationExperiences: [],
    // 技能证书
    skills: [],
	// 资格证书
	professional:[],
    // 项目经历
    projectExperiences: [],
    // 自我评价
    selfEvaluation: '',
    // 求职意向
    jobIntention: {
      position: '', // 期望职位
      industry: '', // 期望行业
      city: '', // 期望城市
      salary: '', // 期望薪资
      arrivalTime: '', // 到岗时间
      jobType: 'fulltime', // 工作类型：fulltime-全职，parttime-兼职，intern-实习
      otherRequirements: '', // 其他要求
    },
	internExperiences:'',
	volunteerExperiences:'',
	campusExperience:[],
    // 模块管理saveToStorage
    modules: [
      { modelName: '个人信息', active: true, sortNum: 1, removable: false, modelId:'' },
      { modelName: '求职意向', active: true, sortNum: 2, removable: true, modelId:'' },
      { modelName: '工作经历', active: true, sortNum: 3, removable: true, modelId:'' },
      { modelName: '教育经历', active: true, sortNum: 4, removable: true, modelId:'' },
      { modelName: '项目经历', active: true, sortNum: 5, removable: true, modelId:'' },
      { modelName: '专业技能', active: true, sortNum: 6, removable: true, modelId:'' },
      { modelName: '资格证书', active: true, sortNum: 7, removable: true, modelId:'' },
      { modelName: '自我评价', active: true, sortNum: 8, removable: true, modelId:'' },
      { modelName: '校园经历', active: false, sortNum: 9, removable: true, modelId:'' },
      { modelName: '实习经历', active: false, sortNum: 10, removable: true, modelId:'' },
      { modelName: '兴趣爱好', active: false, sortNum: 11, removable: true, modelId:'' }
    ]
  }),
  
  actions: {
	// 新增简历
	addResumeFun(data) {
		addResume(data).then(res => {
			if(res.code === 200) {
				this.resumeId = res.data
				this.modules.forEach(async item => {
					if(item.active) {
						addResumeModel({resumeId:res.data,modelName:item.modelName}).then(res => {
							if(res.code === 200) {
								console.log(res)
								item.modelId = res.data
							}
						})
					}
				})
			}
		})
	},
	// 新增模块
	addResumeModelFun(data) {
		return new Promise((resolve, reject) => {
			addResumeModel(data).then(res => {
				if(res.code === 200) {
					// 更新模块的modelId
					const module = this.modules.find(m => m.modelName === data.modelName)
					if (module) {
						module.modelId = res.data
					}
					resolve(res)
				} else {
					reject(new Error(res.message || '添加模块失败'))
				}
			}).catch(err => {
				reject(err)
			})
		})
	},
	// 删除模块
	detResumeModelFun(modelId) {
		return new Promise((resolve, reject) => {
			detResumeModel(modelId).then(res => {
				if(res.code === 200) {
					// 清除模块的modelId
					const module = this.modules.find(m => m.modelId === modelId)
					if (module) {
						module.modelId = ''
					}
					resolve(res)
				} else {
					reject(new Error(res.message || '删除模块失败'))
				}
			}).catch(err => {
				reject(err)
			})
		})
	},
	// 保存模块状态
	saveModuleState() {
		return JSON.parse(JSON.stringify(this.modules))
	},
	// 恢复模块状态
	restoreModuleState(state) {
		this.modules = JSON.parse(JSON.stringify(state))
	},
    // 设置模板信息
    setTemplate(template) {
      this.template = { ...this.template, ...template }
    },
    
    // 设置个人信息
    setPersonalInfo(info) {
      this.personalInfo = { ...this.personalInfo, ...info }
    },
    
    // 添加工作经历
    addWorkExperience(experience) {
      this.workExperiences.push({
        id: Date.now().toString(),
        ...experience
      })
    },
    
    // 更新工作经历
    updateWorkExperience(id, experience) {
      const index = this.workExperiences.findIndex(item => item.id === id)
      if (index !== -1) {
        this.workExperiences[index] = { ...this.workExperiences[index], ...experience }
      }
    },
    
    // 删除工作经历
    deleteWorkExperience(id) {
      this.workExperiences = this.workExperiences.filter(item => item.id !== id)
    },
    
    // 添加教育经历
    addEducationExperience(experience) {
      this.educationExperiences.push({
        id: Date.now().toString(),
        ...experience
      })
    },
    
    // 更新教育经历
    updateEducationExperience(id, experience) {
      const index = this.educationExperiences.findIndex(item => item.id === id)
      if (index !== -1) {
        this.educationExperiences[index] = { ...this.educationExperiences[index], ...experience }
      }
    },
    
    // 删除教育经历
    deleteEducationExperience(id) {
      this.educationExperiences = this.educationExperiences.filter(item => item.id !== id)
    },
    
    // 添加技能证书
    addSkill(skill) {
      this.skills.push({
        id: Date.now().toString(),
        ...skill
      })
    },
    
    // 更新技能证书
    updateSkill(id, skill) {
      const index = this.skills.findIndex(item => item.id === id)
      if (index !== -1) {
        this.skills[index] = { ...this.skills[index], ...skill }
      }
    },
    
    // 删除技能证书
    deleteSkill(id) {
      this.skills = this.skills.filter(item => item.id !== id)
    },
    
    // 添加项目经历
    addProjectExperience(experience) {
      this.projectExperiences.push({
        id: Date.now().toString(),
        ...experience
      })
    },
    
    // 更新项目经历
    updateProjectExperience(id, experience) {
      const index = this.projectExperiences.findIndex(item => item.id === id)
      if (index !== -1) {
        this.projectExperiences[index] = { ...this.projectExperiences[index], ...experience }
      }
    },
    
    // 删除项目经历
    deleteProjectExperience(id) {
      this.projectExperiences = this.projectExperiences.filter(item => item.id !== id)
    },
    
    // 设置自我评价
    setSelfEvaluation(evaluation) {
      this.selfEvaluation = evaluation
    },
    
    // 设置求职意向
    setJobIntention(intention) {
      this.jobIntention = { ...this.jobIntention, ...intention }
    },
	
	getResumeModelListfun() {
		getResumeModelList().then(res=> {
			console.log(res)
		})
	},
    
    // 更新模块状态
    updateModuleStatus(id, active) {
      const index = this.modules.findIndex(item => item.modelId === id)
      if (index !== -1) {
        this.modules[index].active = active
      }
    },
    
    // 更新模块排序
    updateModuleSort(modules) {
      this.modules = modules.map((item, index) => {
        return {
          ...item,
          sortNum: index + 1
        }
      })
    },
    
    // 从本地存储加载数据
    loadFromStorage() {
      try {
        const resumeData = uni.getStorageSync('resumeData')
        if (resumeData) {
          const data = JSON.parse(resumeData)
          Object.keys(data).forEach(key => {
            if (this[key] !== undefined) {
              this[key] = data[key]
            }
          })
        }
      } catch (e) {
        console.error('Failed to load resume data from storage', e)
      }
    },
    
    // 保存数据到本地存储
    saveToStorage() {
      try {
        const data = {
          template: this.template,
          personalInfo: this.personalInfo,
          workExperiences: this.workExperiences,
          educationExperiences: this.educationExperiences,
          skills: this.skills,
          professional: this.professional,
          projectExperiences: this.projectExperiences,
          selfEvaluation: this.selfEvaluation,
          internExperiences: this.internExperiences,
          volunteerExperiences: this.volunteerExperiences,
          campusExperience: this.campusExperience,
          modules: this.modules
        }
        uni.setStorageSync('resumeData', JSON.stringify(data))
      } catch (e) {
        console.error('Failed to save resume data to storage', e)
      }
    }
  }
}) 